import React, { PureComponent, useState } from 'react'
const ThemeContext = React.createContext()
const { Provider, Consumer } = ThemeContext

// 上下文只能类组件才有
class Child extends PureComponent {
    render() {
        // console.log(this)
        return (
            <Consumer>
                {
                    (ctx) => {
                        return (
                            <div style={ctx}>
                                <h3>子组件</h3>
                            </div>
                        )
                    }
                }
            </Consumer>
        )
    }
}

function Parent(props) {
    return (
        <div>
            <h3>父组件</h3>
            <Child />
        </div>

    )
}

function ThemeToggle({ theme, onChange }) {
    let change = (e) => {
        let key = e.target.name
        let val = e.target.value
        onChange({ ...theme, [key]: val })
    }
    return (
        <>
            <div>
                前景色：<input type="color" name='color' value={theme.color} onChange={change} />
                背景色：<input type="color" name='background' value={theme.background} onChange={change} />
            </div>
        </>
    )
}

function PageA() {
    // 在JSX中是不能直接渲染一个对象,但是可以渲染一个数组
    const [theme, setTheme] = useState({ color: '#000000', background: '#ffffff' })
    return (
        <Provider value={theme}>
            <div>
                <h2>change color</h2>
                <hr />
                <Parent />
                <ThemeToggle theme={theme} onChange={e => setTheme(e)} />
            </div>
        </Provider>
    )
}

export default PageA